<template>
  <div>
    <a-upload
      :action="uploadUrl"
      :headers="headers"
      :beforeUpload="beforeUpload"
      list-type="picture-card"
      :file-list="fileList"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="fileList.length < length">
        <template v-if="!head">
          <a-icon type="plus" />
          <div class="ant-upload-text">上传</div>
        </template>
        <template v-if="head">
          <img :src="defaultAvatar" />
        </template>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel" width="800px">
      <img style="width: 100%; padding: 15px;" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import { VERSION_NO, APP_KEY, REQUEST_INTEFACE_URL } from '@/common/config'
import md5 from 'md5'
import store from 'store'
import Util from '@/common/util'
import defaultAvatar from '@/../static/images/defaultAvatar.png'

const getBase64 = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
const smallSuffix = '?x-oss-process=image/resize,h_100' // 压缩预览图片

export default {
  name: 'upload',
  props: {
    uploadName: '',
    length: {
      type: Number,
      default: 100
    },
    fatherList: {
      type: Array,
      default: () => {
        return []
      }
    },
    optList: {
      type: Array,
      default: () => {
        return []
      }
    },
    head: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      fileList: [],
      previewVisible: false,
      previewImage: '',
      headers: {},
      uploadUrl: REQUEST_INTEFACE_URL + '/file/upload',
      defaultAvatar
    }
  },
  methods: {
    beforeUpload () {
      const uuid = Util.getUUID()
      const headers = {
        appKey: APP_KEY,
        version: VERSION_NO,
        timestamp: (() => new Date().getTime())(),
        nonce: uuid,
        token: store.get('token') ? store.get('token') : '',
        sign: md5(`appKey${APP_KEY}nonce${uuid}timestamp${new Date().getTime()}84001ac0d7064aea883e8f6623ceb82b`).toUpperCase()
      }
      this.headers = headers
    },
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = (file.url ? file.url.replace(smallSuffix, '') : '') || file.preview
      this.previewVisible = true
    },
    handleChange ({ file, fileList }) {
      this.fileList = fileList
      console.log(file.status, '-', fileList.length > 0 ? fileList[0].status : '')
      if (file.status === 'done' || file.status === 'removed') {
        let picList = []
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].response) {
            picList.push(fileList[i].response.data.url)
          } else {
            picList.push(fileList[i].url.replace(smallSuffix, ''))
          }
        }
        this.$emit('uploadFile', picList.join(','))
      }
    }
  },
  mounted () {
    let picList = this.fatherList
    let initPics = []
    if (picList.length > 0) {
      for (let i = 0; i < picList.length; i++) {
        let pic = picList[i]
        let picType = pic.substr(pic.lastIndexOf('/')).split('.')[1]
        let picObj = {
          uid: i,
          name: `image.${picType}`,
          status: 'done',
          url: `${pic}${smallSuffix}`
        }
        initPics.push(picObj)
      }
    }
    this.fileList = initPics
  },
  watch: {
    optList () {
      let picList = this.optList
      let optListT = []
      if (picList.length > 0) {
        for (let i = 0; i < picList.length; i++) {
          let pic = picList[i]
          let picType = pic.substr(pic.lastIndexOf('/')).split('.')[1]
          let picObj = {
            uid: i,
            name: `image.${picType}`,
            status: 'done',
            url: `${pic}${smallSuffix}`
          }
          optListT.push(picObj)
        }
      }
      this.fileList = optListT
    }
  }
}
</script>

<style lang="less" scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
